package com.yufu.idaas.sdk.service;

import com.yufu.idaas.sdk.constants.SDKRole;
import com.yufu.idaas.sdk.exception.GenerateException;
import com.yufu.idaas.sdk.exception.YufuInitException;
import com.yufu.idaas.sdk.init.YufuAuth;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;


import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static com.yufu.idaas.sdk.constants.YufuTokenConstants.APP_INSTANCE_ID_KEY;

@Resource
public class DismissService {
    private static YufuAuth yufuAuth;
    static public String getDismissUrl(final String userId, final String displayName){
        File file = null;
        String keyPath=null;
        try {
            file = ResourceUtils.getFile("classpath:keys/rsa_private_key.pem");
            keyPath = file.getCanonicalPath();
            System.out.println(keyPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            yufuAuth = YufuAuth.builder()
                    .issuer("16151655944") //SDKID（客户的sdkid）
                    .sdkRole(SDKRole.IDP)
                    .tnt("testTenant")
                    .privateKeyPath(keyPath)
                    .keyFingerPrint("")
                    .build();
        } catch (YufuInitException e) {
            e.printStackTrace();
        }
        Map<String, Object> claims = new HashMap<String, Object>() {
            {
                put(APP_INSTANCE_ID_KEY, "testAppInstanceId");
                put("sub", userId); //登录用户名
                put("name", displayName); //显示名
            }
        };
        URL url = null;
        try {
            url = yufuAuth.generateIDPRedirectUrl(claims);
        } catch (GenerateException e) {
            e.printStackTrace();
        }

        String query = url.getQuery();
        String idpToken = query.substring(query.indexOf("idp_token=") + "idp_token=".length());

        String chit_url=" https://chit-idp.id.meeting.qq.com/cidp/custom/ai-a82c542905c64de480e26dc6929b5612/ai-4244f22a07bb4cd6aa7c97670747923d?id_token=";

        String sso_user_url=chit_url+idpToken;
        System.out.println(sso_user_url);
        return sso_user_url;    }


    public static void main(String[] args) {

        String dismissUrl = DismissService.getDismissUrl("sunhongyu","孙宏宇");

    }
}